<!--录像回放-->
<template>
  <div>
    <Modal v-model="modal.show"  :loading="modal.loading" :title="modal.title"  :mask-closable="false" :footer-hide=true width="1080" :closable="false">
      <div style="height:600px;width:100%;display: flex">
        <!-- 文件列表       -->
        <div ref="left-side"  style="width: 17%;height: 100%;display: flex;flex-direction: column">
          <DatePicker v-model="queryDate" format="yyyy-MM-dd" type="date" :placeholder="$t('datepicker')" style="width: 100%" @on-change="queryRecord"></DatePicker>
          <div class="sider-record-list">
            <ul v-if="recordList.length >0" >
              <li v-for="item in recordList" >
                <Tag checkable style="cursor: pointer" :checked="item.checked" v-if="chooseFile !== item" color= "blue" @on-change="checkedFile(item,1)">
                  <Icon type="ios-videocam" />
                  {{item.recordTitle}}
                </Tag>
                <Tag checkable style="cursor: pointer" :checked="item.checked" v-if="chooseFile === item" color="magenta" >
                  <Icon type="ios-videocam" />
                  {{item.recordTitle}}
                </Tag>
                <Icon type="md-download" color="#409EFF" style="color: #3f4244;margin-left: 5px; cursor: pointer" @click="checkedFile(item,2)"/>
              </li>
            </ul>
            <div v-if="recordList.length ===0" >{{$t('no_data')}}</div>
          </div>
        </div>
        <!-- 播放器内容       -->
        <div style="width: 83%;height: 100%;display: flex;flex-direction: column" >
          <RtcWithTalkPlayer :id="player.id"
                             ref="rtcWithTalkPlayer11"
                             :autoReplay="player.autoReplay"
                             :showCustomBar="player.showCustomBar"
                             :muted="player.muted"
                             :videoId="player.videoId"
                             @playCurrentTime="playCurrentTime"
          />

        <!--  控制按钮组合  -->
          <div style="height: 100px;width: 100%">
            <div v-if="1===1" style="width: 100%;height:32px;display: flex;justify-content: center;margin-top: 5px">
              <ButtonGroup size="small" style="margin-right: 5px">
                <TimePicker :disabled="!chooseFile"
                            confirm type="timerange"
                            v-model="play.timerange"
                            placement="bottom-end"
                            :disabled-hours="disabledHours"
                            :disabled-minutes="disabledMinutes"
                            :placeholder="$t('select_time')"
                            @on-change="timeChange"
                            style="height:16px;width: 168px"></TimePicker>
                <Checkbox v-if="1===0" v-model="player.muted">静音</Checkbox>
              </ButtonGroup>

<!--              <ButtonGroup size="default" style="margin-left: 5px">-->
              <div style="display: flex;flex-direction: row;">
                <div v-show="play.processType === 1">
                  <Button :disabled="!chooseFile" v-show="play.playStatus===1" style="margin-left: 5px" :title="$t('pause')" icon="md-pause" @click="gbPause()"></Button>
                  <Button :disabled="!chooseFile" v-show="play.playStatus===0" style="margin-left: 5px" :title="$t('start')" icon="md-play" @click="gbPlay()"></Button>
                  <Button :disabled="!chooseFile" v-show="play.playStatus===2" style="margin-left: 5px" :title="$t('resume')" icon="ios-play-outline" @click="gbResume()"></Button>
                  <Button :disabled="!chooseFile" v-show="play.playStatus===1" style="margin-left: 5px" :title="$t('stop')" icon="md-square" @click="gbStop()"></Button>
                </div>
                <div v-show="play.processType === 2" style="display: flex;flex-direction: row;align-items: center">
                  <Button :disabled="!chooseFile" v-show="play.playStatus===0"style="margin-left: 5px" icon="md-download" :title="$t('download_video')" @click="downloadRecord()"></Button>
                  <Button :disabled="!chooseFile" v-show="play.playStatus===1" style="margin-left: 5px" :title="$t('stop')" icon="md-square" @click="gbStop()"></Button>
<!--                  <Icon type="md-download" color="red" style="cursor: pointer"/>-->
                  <span style="margin-left:7px;color: #c80000">{{play.time}}</span>
                </div>
<!--                <Button style="margin-left: 5px" icon="md-refresh" :title="$t('refresh')" @click="refresh()"></Button>
                <Button @click="queryDwFiles" icon="ios-browsers" :title="$t('browse')"></Button>-->

                <Dropdown :disabled="true" @on-click="gbScale">
                  <Button style="margin-left: 5px" size="default" :title="$t('double_speed_play')" icon="ios-arrow-down" >{{$t('double_speed_play')}}</Button>
                  <DropdownMenu :disabled="true" slot="list">
                    <DropdownItem :disabled="true" name="0.25">{{$t('speed_0_25X')}}</DropdownItem>
                    <DropdownItem :disabled="true" name="0.5">{{$t('speed_0_5X')}}</DropdownItem>
                    <DropdownItem :disabled="true" name="1.0">{{$t('speed_1X')}}</DropdownItem>
                    <DropdownItem :disabled="true" name="2.0">{{$t('speed_2X')}}</DropdownItem>
                    <DropdownItem :disabled="true" name="4.0">{{$t('speed_4X')}}</DropdownItem>
                  </DropdownMenu>
                </Dropdown>

                <Button :disabled="true" style="margin-left: 5px" v-if="slider.sliderMIn === 0 && slider.sliderMax === 86400" icon="md-expand" :title="$t('zoom_in')" @click="setSliderFit()"></Button>
                <Button :disabled="!chooseFile" style="margin-left: 5px" v-if="slider.sliderMIn !== 0 || slider.sliderMax !== 86400" class="iconfont icon-slider-right" :title="$t('zoom_reset')" @click="setSliderFit()"></Button>
                <Button style="margin-left: 5px" icon="md-refresh" :title="$t('refresh')" @click="refresh()"></Button>
                <Button style="margin-left: 5px" icon="ios-browsers" :title="$t('browse')" @click="queryDwFiles()"/>


                <!--              </ButtonGroup>-->
                </div>
            </div>
            <div style="display: flex;justify-content: center">
              <Slider style="width: 95%"
                      show-tip="never"
                      :min="slider.sliderMIn" :max="slider.sliderMax" :step="3600" range
                      v-model="slider.playTime"
                :marks="slider.marks"
              ></Slider>
            </div>
          </div>
        </div>
      </div>
      <Row>
        <Col span="8">
          <template>
            <div>
              <input ref="fileUpload" type="file" webkitdirectory directory multiple @change="handleFiles" @onblur="onblur "
                     style="display: none"
              >
<!--              <ul>
                <li v-for="file in files" :key="file.name">{{ file.name }}</li>
              </ul>-->
            </div>
          </template>
        </Col>
        <Col span="8">

        </Col>
        <Col span="8">

        </Col>
      </Row>
      <Row>
        <Col span="24">
          <div style="display: flex;justify-content: center">
            <Button type="primary" @click="close">{{$t('close')}}</Button>
          </div>
        </Col>
      </Row>
    </Modal>
    <RecordDownload ref="recordDownload"></RecordDownload>
    <DownloadFiles ref="downloadFiles"></DownloadFiles>
  </div>
</template>
<script>
import GbRecord from "@/api/GbRecord"
import Device from "@/api/Device"
import RtcWithTalkPlayer from '@/view/Home/component/RtcWithTalkPlayer.vue';
import RecordDownload from "@/view/Home/utils/RecordDownload";
import moment from "moment";
import {apiResult} from "@/libs/util";
import DownloadFiles from "@/view/Home/utils/DownloadFiles";
export default {
  components:{RtcWithTalkPlayer,RecordDownload,DownloadFiles},
  name:"VideoReplay",
  watch:{
    mediaReplayFinish(n,o){
      //console.log("mediaReplayFinish: %o",n)
      if (!!n && !!n.deviceCode && n.deviceCode === this.deviceData.arrt.deviceCode){
        //播放结束，被近停止
        this.gbStop0();
      }
    }
  },
  computed:{
    mediaReplayFinish(){
      return this.$store.getters.getMediaReplayFinish;
    }
  },
  data(){
    return{
      api: new GbRecord(),
      deviceApi: new Device(),
      player:{
        muted:false,
        autoReplay:false,
        showCustomBar:false,
        id:1,
        videoId:"rtcWithTalkPlayer11",
        videoPlayer:null,
        delayTimer:null,
      },
      modal:{
        show: false,
        loading: false,
        title: '',
      },
      queryDate:null,
      deviceData:null,
      recordInfo:null,
      recordList:[],
      chooseFile:null,
      slider:{
        playTime:0,
        sliderMIn: 0,
        sliderMax: 86400,
        marksColor: "00060c",
        marks: {
          0: {style: {color: '#ff0000',fontSize:'10px'},label: '00:00'},
          3600: {style: {color: '#00060c',fontSize:'10px'},label: '01:00'},
          7200: {style: {color: '#00060c',fontSize:'10px'},label: '02:00'},
          10800: {style: {color: '#00060c',fontSize:'10px'},label: '03:00'},
          14400: {style: {color: '#00060c',fontSize:'10px'},label: '04:00'},
          18000: {style: {color: '#00060c',fontSize:'10px'},label: '05:00'},
          21600: {style: {color: '#00060c',fontSize:'10px'},label: '06:00'},
          25200: {style: {color: '#00060c',fontSize:'10px'},label: '07:00'},
          28800: {style: {color: '#00060c',fontSize:'10px'},label: '08:00'},
          32400: {style: {color: '#00060c',fontSize:'10px'},label: '09:00'},
          36000: {style: {color: '#00060c',fontSize:'10px'},label: '10:00'},
          39600: {style: {color: '#00060c',fontSize:'10px'},label: '11:00'},
          43200: {style: {color: '#00060c',fontSize:'10px'},label: '12:00'},
          46800: {style: {color: '#00060c',fontSize:'10px'},label: '13:00'},
          50400: {style: {color: '#00060c',fontSize:'10px'},label: '14:00'},
          54000: {style: {color: '#00060c',fontSize:'10px'},label: '15:00'},
          57600: {style: {color: '#00060c',fontSize:'10px'},label: '16:00'},
          61200: {style: {color: '#00060c',fontSize:'10px'},label: '17:00'},
          64800: {style: {color: '#00060c',fontSize:'10px'},label: '18:00'},
          68400: {style: {color: '#00060c',fontSize:'10px'},label: '19:00'},
          72000: {style: {color: '#00060c',fontSize:'10px'},label: '20:00'},
          75600: {style: {color: '#00060c',fontSize:'10px'},label: '21:00'},
          79200: {style: {color: '#00060c',fontSize:'10px'},label: '22:00'},
          82800: {style: {color: '#00060c',fontSize:'10px'},label: '23:00'},
          86400: {style: {color: '#00060c',fontSize:'10px'},label: '24:00'},
        },
      },
      queryParam:{
        from:null,
        to:null
      },
      stream:{
        streamInfo:null,
        app:null,
        streamId:null,
        mediaServerId:null,
        //ssrc:null,
        videoUrl:null,
        hasAudio:false
      },
      play:{
        startTime:null,
        endTime:null,
        protocol: "rtc",
        //playTime:0,
        time:"00:00:00",
        timerange:[],
        processType: 0,//0什么也没做，1正录像，2正在下载
        playStatus: 0,//状态，0 未播放，1正播放，2暂停

      },
      isHttps:false,
      disabledHours:[],
      disabledMinutes:[],
      recorder:null,
      files:[]
    }
  },
  methods: {
    refresh(){
      this.$refs.fileUpload.click();
    },
    queryDwFiles(){
      this.$refs.downloadFiles.openDialog(this.files)
    },
    onblur(event){
      //console.log("onblur: %o",event.target.files);
    },
    handleFiles(event) {
      //console.log("event.target.files: %o",event.target.files);
      this.files=[];
      const fs = event.target.files;

      //const files = []; // Clear the current list of files to avoid duplicates
      if (!!fs && fs.length > 0){
        for (let i = 0; i < fs.length; i++) {
          if (fs[i].type == 'video/mp4'){
            this.files.push(
              {
                name: fs[i].name,
                type: fs[i].type,
                size: (fs[i].size / 1000 / 1000.0).toFixed(3) + "M",
                time: moment(fs[i].lastModified).format("YYYY-MM-DD HH:mm:ss"),
                file: fs[i]
              }
            );
          }
          console.log()
          //this.play.timerange = [moment(startTime).format("HH:mm:ss"), moment(endTime).format("HH:mm:ss")]
          //const t = (new Date(startTime).getTime() - new Date(this.queryParam.from).getTime()) / 1000;
        }

      }

/*      for (let i = 0; i < files.length; i++) {
        tableData.push(files[i]);
      }*/
    },

    gbResume() {
      //继续
      this.api.resume(JSON.stringify({
        deviceCode: this.deviceData.arrt.deviceCode,
        streamId: this.stream.streamId
      })).then(res => {
        apiResult(res.data, false, result => {
          this.$refs["rtcWithTalkPlayer11"].playByUrl(this.stream.videoUrl)
          this.play.playStatus = 1;
          this.play.processType = 1;
        });
      })
    },
    gbPlay() {
      let today = this.queryDate;
      const time1 = this.play.timerange[0].split(":")
      today.setHours(time1[0]);
      today.setMinutes(time1[1]);
      today.setSeconds(time1[2]);
      today.setMilliseconds(0);
      this.play.startTime = moment(today).format("YYYY-MM-DD HH:mm:ss")
      const time2 = this.play.timerange[1].split(":")
      today.setHours(time2[0]);
      today.setMinutes(time2[1]);
      today.setSeconds(time2[2]);
      today.setMilliseconds(999);
      this.play.endTime = moment(today).format("YYYY-MM-DD HH:mm:ss")

      const t = (new Date(this.play.startTime).getTime() - new Date(this.queryParam.from).getTime()) / 1000;
      let start = Math.floor(t / 3600) * 3600;
      const t1 = (new Date(this.play.endTime).getTime() - new Date(this.queryParam.from).getTime()) / 1000;
      let end = Math.floor(t1 / 3600) * 3600;
      if (start === end) end = start + 3600;
      //显示条上显示的时间
      this.slider.playTime = [start, end];

      //访问后台 start
      const param = {
        deviceCode: this.deviceData.arrt.deviceCode,
        channelCode: this.deviceData.arrt.channelCode,
        fromTime: this.play.startTime,
        toTime: this.play.endTime
      };
      this.api.start(JSON.stringify(param)).then(res => {
        apiResult(res.data, false, result => {
          this.stream.streamInfo = res.data.data;
          this.stream.app = this.stream.streamInfo.app;
          this.stream.streamId = this.stream.streamInfo.stream;
          this.stream.mediaServerId = this.stream.streamInfo.mediaServerId;
          this.stream.hasAudio = this.stream.streamInfo.tracks && this.stream.streamInfo.tracks.length > 1
          this.player.muted = !this.hasAudio;
          //this.stream.ssrc = this.streamInfo.ssrc;
          if (!!this.stream.streamInfo[this.play.protocol]) {
            const playUrl = res.data.data[this.play.protocol];
            this.stream.videoUrl = this.deviceApi.getPlayUrl(playUrl);
            this.$refs.rtcWithTalkPlayer11.playByUrl(this.stream.videoUrl);
            this.play.playStatus = 1;
            this.play.processType = 1;
            //console.log("getPlayUrl: %o",this.stream.videoUrl)
          }
        });
      });

    },
    gbPause() {
      //console.log('前端控制：暂停');
      this.api.pause(JSON.stringify({
        deviceCode: this.deviceData.arrt.deviceCode,
        streamId: this.stream.streamId
      })).then(res => {
        apiResult(res.data, false, result => {
          this.$refs.rtcWithTalkPlayer11.stop();
          this.play.playStatus = 2;
          this.play.processType = 1;
        });
      })
    },
    gbScale(command) {
      console.log('前端控制：倍速 ' + command);
      this.api.speed(JSON.stringify({streamId: this.stream.streamId, command: command})).then(res => {
        {
        }
      })
    },
    gbStop() {

      //回放
      if (this.play.processType === 1) {
        this.api.stop(JSON.stringify({
          deviceCode: this.deviceData.arrt.deviceCode,
          channelCode: this.deviceData.arrt.channelCode,
          streamId: this.stream.streamId
        })).then(res => {
          apiResult(res.data, false, result => {
            this.$refs.rtcWithTalkPlayer11.stop();
            this.play.playStatus = 0;
            this.play.processType = 1;
          });
        })
        //下载
      } else if (this.play.processType === 2) {
        this.api.downloadStop(JSON.stringify({
          deviceCode: this.deviceData.arrt.deviceCode,
          channelCode: this.deviceData.arrt.channelCode,
          streamId: this.stream.streamId
        })).then(res => {
          apiResult(res.data, false, result => {
            this.$refs.rtcWithTalkPlayer11.stop();
            this.play.playStatus = 0;
            this.play.processType = 2;
          });
        })
      }

    },
    gbStop0() {
      console.log(">>>>>> gbStop0，recorder=%o",this.recorder)
      this.$refs.rtcWithTalkPlayer11.stop();
      if (!!this.recorder){
        console.log(">>>>>> recorder.stop()")
        this.recorder.stop();
      }
      this.play.playStatus = 0;
      //this.play.processType = 1;
      /*      this.$refs.rtcWithTalkPlayer11.stop();
      this.recordList.forEach(item=>{
        item.checked = true;
      })
      this.chooseFile = null;*/
    },
    openDialog(data) {
      this.files=[];
      //console.log(">>>>>> openDialog.data=%o", data);
      this.recorder = null;


      this.play.playStatus = 0;
      this.play.processType = 1;
      this.play.time = "00:00:00";
      this.chooseFile = null;
      this.player.muted = false; //关闭语音
      //this.player.muted = false; //开启语音
      this.deviceData = data;
      this.modal.show = true;
      this.autoReplay = false; //播放完成不自动重播
      if (this.queryDate != null) {
        this.queryRecord();
      }
    },

    /**
     * 选择文件
     * 1 回放  2 下载
     */
    checkedFile(file, mode) {
      if (this.play.processType === mode && this.chooseFile === file) {
        return;
      }
      if (this.play.playStatus !== 0) {
        this.gbStop();
      }

      this.play.processType = mode;
      this.chooseFile = file;
      this.recordList.forEach(item => {
        if (item === file) {
          item.checked = true;
        } else {
          item.checked = false;
        }
      })
      this.setTime(file.startTime, file.endTime);

      if (mode === 1) { //回放
        this.playRecord();
      } else if (mode === 2) { //下载
        this.downloadRecord(file)
      }
    },
    /**
     *  点文件播放
     */
    /*checkedPlayFile(file){
      //console.log("file=%o",file)
      //文件已在播放
      //if (this.chooseFile === file){return;}
      this.chooseFile = file;
      this.recordList.forEach(item=>{
        if (item === file){
          item.checked = true;
        }else{
          item.checked = false;
        }
      })
      this.setTime(file.startTime, file.endTime);

      // 开始回放
      this.playRecord()
    },*/
    close() {
      if (this.play.playStatus != 0) {
        this.gbStop();
      }
      this.$refs.rtcWithTalkPlayer11.stop();
      this.modal.show = false
    },
    stopPlayRecord: function (callback) {
      console.log("停止录像回放")
      if (this.stream.streamId !== "") {
        this.$refs["rtcWithTalkPlayer11"].stop();
        this.stream.videoUrl = '';
        const param = {
          deviceCode: this.deviceData.arrt.deviceCode,
          channelCode: this.deviceData.arrt.channelCode,
          streamId: this.stream.streamId
        };
        this.api.stop(JSON.stringify(param)).then(res => {
          if (callback) callback();
        })
      }
    },
    playRecord() {
      //console.log("this.stream.streamId: %o",this.stream.streamId)
      this.stream.streamId = null;
      const _this = this;
      if (!!this.stream.streamId) {
        this.stopPlayRecord(() => {
          this.stream.streamId = "";
          this.playRecord();
        })
      } else {
        const param = {
          deviceCode: this.deviceData.arrt.deviceCode,
          channelCode: this.deviceData.arrt.channelCode,
          fromTime: this.play.startTime,
          toTime: this.play.endTime
        };
        this.api.start(JSON.stringify(param)).then(res => {
          apiResult(res.data, false, result => {
            this.stream.streamInfo = res.data.data;
            this.stream.app = this.stream.streamInfo.app;
            this.stream.streamId = this.stream.streamInfo.stream;
            this.stream.mediaServerId = this.stream.streamInfo.mediaServerId;
            this.stream.hasAudio = this.stream.streamInfo.tracks && this.stream.streamInfo.tracks.length > 1
            //this.stream.ssrc = this.streamInfo.ssrc;
            if (!!this.stream.streamInfo[_this.play.protocol]) {
              const playUrl = res.data.data[_this.play.protocol];
              this.stream.videoUrl = this.deviceApi.getPlayUrl(playUrl);
              this.$refs.rtcWithTalkPlayer11.playByUrl(this.stream.videoUrl);
              this.play.playStatus = 1;
              this.play.processType = 1;
              //console.log("getPlayUrl: %o",this.stream.videoUrl)
            }
          });
        });
      }
    },
    playCurrentTime(currentTime) {
      //console.log(currentTime)
      this.play.time = currentTime;
    },
    setTime: function (startTime, endTime) {
      let fromTime = this.queryDate;
      fromTime.setHours(0);
      fromTime.setMinutes(0);
      fromTime.setSeconds(0);
      fromTime.setMilliseconds(0);
      this.queryParam.from = moment(fromTime).format("YYYY-MM-DD HH:mm:ss")
      //this.queryParam.from = fromTime.toLocaleString('zh-CN', { year: 'numeric', month: '2-digit', day: '2-digit', hour: '2-digit', minute: '2-digit', second: '2-digit' });;
      let toTime = this.queryDate;
      toTime.setHours(23);
      toTime.setMinutes(59);
      toTime.setSeconds(59);
      toTime.setMilliseconds(999);
      this.queryParam.to = moment(toTime).format("YYYY-MM-DD HH:mm:ss")
      console.log("startTime=%o;endTime=%o", startTime, endTime)
      this.play.startTime = startTime;
      this.play.endTime = endTime;
      this.play.timerange = [moment(startTime).format("HH:mm:ss"), moment(endTime).format("HH:mm:ss")]
      const t = (new Date(startTime).getTime() - new Date(this.queryParam.from).getTime()) / 1000;
      let start = Math.floor(t / 3600) * 3600;
      const t1 = (new Date(endTime).getTime() - new Date(this.queryParam.from).getTime()) / 1000;
      let end = Math.floor(t1 / 3600) * 3600;
      if (start === end) end = start + 3600;

      console.log("start=%o;end=%o", start, end);

      //显示条上显示的时间
      this.slider.playTime = [start, end];

      /*      this.startTime = startTime;
      this.endTime = endTime;
      let start = (new Date(this.startTime).getTime() - new Date(this.chooseDate + " 00:00:00").getTime())/1000;
      let end = (new Date(this.endTime).getTime() - new Date(this.chooseDate + " 00:00:00").getTime())/1000;

      this.playTime = [start, end];
      this.timeRange = [startTime, endTime];*/
    },

    queryRecord() {
      if (!this.queryDate) {
        return;
      }

      let fromTime = this.queryDate;
      fromTime.setHours(0);
      fromTime.setMinutes(0);
      fromTime.setSeconds(0);
      fromTime.setMilliseconds(0);
      //const from = fromTime.toLocaleString('zh-CN', { year: 'numeric', month: '2-digit', day: '2-digit', hour: '2-digit', minute: '2-digit', second: '2-digit' });;
      const from = moment(fromTime).format("YYYY-MM-DD HH:mm:ss")
      let toTime = this.queryDate;
      toTime.setHours(23);
      toTime.setMinutes(59);
      toTime.setSeconds(59);
      toTime.setMilliseconds(999);
      //const to = toTime.toLocaleString('zh-CN', { year: 'numeric', month: '2-digit', day: '2-digit', hour: '2-digit', minute: '2-digit', second: '2-digit' });;
      const to = moment(toTime).format("YYYY-MM-DD HH:mm:ss")
      /*      console.log(from);
      console.log(to);
      console.log(this.deviceData.arrt.deviceCode);
      console.log(this.deviceData.arrt.channelCode);*/
      //this.setTime()
      const param = {
        deviceCode: this.deviceData.arrt.deviceCode,
        channelCode: this.deviceData.arrt.channelCode,
        fromTime: from,
        toTime: to
      };
      this.api.query(JSON.stringify(param)).then(res => {
        apiResult(res.data, false, result => {
          this.recordInfo = res.data.data;
          this.recordList = res.data.data.recordList;
          this.recordList.forEach(item => {
            item["recordTitle"] = moment(item.startTime).format('HH:mm:ss') + "-" + moment(item.endTime).format('HH:mm:ss');
            item["checked"] = false;
          })

        })
      });

      //http://192.168.0.129:18080/api/gb_record/query/44010200492000000020/44030000492000000020?startTime=2024-01-16%2000:00:00&endTime=2024-01-16%2023:59:59

    },
    timeChange(val) {
      console.log("timeChange,val=%o", val);
      console.log("timeChange,timerange=%o", this.play.timerange);
      //this.setTime(val[0], val[1])
    },
    //下载
    downloadRecord: function () {
      /*if (this.play.playStatus !== 0){
        this.gbStop();
      }
      this.chooseFile = null;
      //if (this.chooseFile === file){return;}
      this.chooseFile = file;
      this.recordList.forEach(item=>{
        if (item === file){
          item.checked = true;
        }else{
          item.checked = false;
        }
      })
      this.setTime(file.startTime, file.endTime);
*/
      const param = {
        deviceCode: this.deviceData.arrt.deviceCode,
        channelCode: this.deviceData.arrt.channelCode,
        fromTime: this.play.startTime,
        toTime: this.play.endTime
      };
      this.api.downloadStart(JSON.stringify(param)).then(res => {
        apiResult(res.data, false, result => {
          console.log(result);
          this.stream.streamInfo = result.data;
          this.stream.app = this.stream.streamInfo.app;
          this.stream.streamId = this.stream.streamInfo.stream;
          this.stream.mediaServerId = this.stream.streamInfo.mediaServerId;
          this.stream.hasAudio = this.stream.streamInfo.tracks && this.stream.streamInfo.tracks.length > 1
          //this.stream.ssrc = this.streamInfo.ssrc;
          if (!!this.stream.streamInfo[this.play.protocol]) {
            const playUrl = res.data.data[this.play.protocol];
            this.stream.videoUrl = this.deviceApi.getPlayUrl(playUrl);
            //录像
            this.$refs.rtcWithTalkPlayer11.recordUrl(this.stream.videoUrl,this.recording);
            this.play.playStatus = 1;
            this.play.processType = 2;
          }
        }, err => {
          console.log("err: %o", err);

        })
      });


      /*      this.$Message.warning("Download function under construction......")
      this.$refs["rtcWithTalkPlayer11"].downloadtest();

      return;
      this.$refs.recordDownload.openDialog(this.deviceData, null, null,null);
      return;
      if (!row) {
        let startTimeStr = moment(new Date(this.queryDate + " 00:00:00").getTime() + this.slider.playTime[0]*1000).format("YYYY-MM-DD HH:mm:ss");
        let endTimeStr = moment(new Date(this.queryDate + " 00:00:00").getTime() + this.slider.playTime[1]*1000).format("YYYY-MM-DD HH:mm:ss");
        console.log(startTimeStr);
        console.log(endTimeStr);
        row = {
          startTime: startTimeStr,
          endTime: endTimeStr
        }
      }

      if (this.streamId !== "") {
        this.stopPlayRecord(()=> {
          this.streamId = "";
          this.downloadRecord(row);
        })
      }else {
        const param = {
          deviceCode:this.deviceData.arrt.deviceCode,
          channelCode:this.deviceData.arrt.channelCode,
          fromTime:row.startTime,
          toTime:row.endTime};
        this.api.downloadStart(JSON.stringify(param)).then(res=>{
          apiResult(res.data,false,result=>{
            let streamInfo = res.data.data;
            this.$refs.recordDownload.openDialog(this.deviceData, streamInfo.app, streamInfo.stream, streamInfo.mediaServerId);
          });
        })
      }*/
    },
    setSliderFit() {
      if (this.sliderMIn === 0 && this.sliderMax === 86400) {
        if (this.recordList.length > 0) {
          let timeForFile = this.getTimeForFile(this.recordList[0]);
          let lastTimeForFile = this.getTimeForFile(this.recordList[this.recordList.length - 1]);
          let timeNum = timeForFile[0].getTime() - new Date(this.queryDate + " " + "00:00:00").getTime()
          let lastTimeNum = lastTimeForFile[1].getTime() - new Date(this.queryDate + " " + "00:00:00").getTime()

          this.slider.playTime = parseInt(timeNum / 1000)
          this.slider.sliderMIn = parseInt(timeNum / 1000 - timeNum / 1000 % (60 * 60))
          this.slider.sliderMax = parseInt(lastTimeNum / 1000 - lastTimeNum / 1000 % (60 * 60)) + 60 * 60

          this.slider.playTime = [this.slider.sliderMIn, this.slider.sliderMax];
        }
      } else {
        this.slider.sliderMIn = 0;
        this.slider.sliderMax = 86400;
      }
    },
    getTimeForFile(file) {
      let startTime = new Date(file.startTime);
      let endTime = new Date(file.endTime);
      return [startTime, endTime, endTime.getTime() - startTime.getTime()];
    },
    downloadTest: function () {
    },


    /**
     * 执行录像
     * @param videoElement video标签
     */
    recording(videoElement) {
      console.log(">>>>>> videoElement： %o", videoElement)
      const currTime = moment(new Date()).format("YYYYMMDDHHmmssSSSS");
      //暂不考虑通道号
      const fileName = this.deviceData.arrt.deviceCode + "_" + currTime + ".mp4";

      console.log(">>>>>> currTime： %o", currTime)
      //录像
      console.log(">>>>>> recording......")
      //取得stream
      videoElement.captureStream = videoElement.captureStream || videoElement.mozCaptureStream;
      const mediaStream = videoElement.captureStream();
      //判断是否支持 哪一种webm
      const mime = MediaRecorder.isTypeSupported("video/webm;codecs=h264")
        ? "video/webm;codecs=h264"
        : "video/webm";
      //console.log(mime);

      let recorder = new MediaRecorder(mediaStream, {mimeType: mime});

      // 音视频 数组
      let chunks = [];
      // 录像事件： 有数据时就加入数组
      recorder.ondataavailable = (event) => {
        console.log(event.data);
        chunks.push(event.data);
      }

      //停止事件
      recorder.onstop = (stream) => {
        console.log(">>>>>> record stop")
        // 获取视频源
        const blob = new Blob(chunks, {type: chunks[0].type});
        //创建URL
        const url = URL.createObjectURL(blob);
        // 创建下载链接
        const downloadLink = document.createElement("a");
        downloadLink.href = url;
        downloadLink.download = fileName;
        // 添加链接到界面
        document.body.appendChild(downloadLink);
        // 触发下载
        downloadLink.click();
        // 清理界面
        document.body.removeChild(downloadLink);

        //释放url对象
        URL.revokeObjectURL(url)
      }
      if (!!recorder)
        recorder.start();

      this.recorder = recorder;
    },
  },
  mounted() {
    this.modal.title=this.$t('replay')
    this.isHttps = 'https:' === document.location.protocol;
    this.play.protocol = this.isHttps?"rtcs":"rtc";



    /** 为了显示用，调置默认值 */
    //const end = new Date();
    const start = new Date();

/*    start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
    start.setHours(0);
    start.setMinutes(0);
    start.setSeconds(0);
    start.setMilliseconds(0);
    end.setHours(23);
    end.setMinutes(59);
    end.setSeconds(59);
    end.setMilliseconds(999);

    this.dateRange=[start, end];*/
    this.queryDate = new Date();
  }
}

</script>
<style lang="less">
.sider-record-list{
  width: 100%;
  height: 100%;
  overflow: auto;
  //滚动条设置
  .sider-record-list::-webkit-scrollbar { /*滚动条整体样式*/
    width: 10px; /*高宽分别对应横竖滚动条的尺寸*/
    height: 10px;
  }

  .sider-record-list::-webkit-scrollbar-thumb { /*滚动条里面小方块*/
    border-radius: 10px;
    -webkit-box-shadow: inset 0 0 5px rgba(0, 0, 0,0.3);
    background: rgba(0, 0, 0,0.1);
  }

}

</style>
